package com.huhu.controller;

import com.huhu.entity.ArticleInfo;
import com.huhu.entity.UserInfo;
import com.huhu.entity.vo.ArticleInfoVO;
import com.huhu.service.ArticleService;
import com.huhu.util.AjaxResult;
import com.huhu.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {
    private final static int MAX_DESCRIPTION_LENGTH=100;    // 跟前端一样,简介最大长度
    @Autowired
    private ArticleService articleService;

    /**
     * 获取我的所有文章
     *
     * @param request
     * @return
     */
    @RequestMapping("/mylist")
    public List<ArticleInfo> getMyList(HttpServletRequest request) {
        // 在session中验证登录状态
        UserInfo userInfo = SessionUtil.getLoginUser(request);
        // 如果获取用户对象为空或者无效对象
        if (userInfo == null || userInfo.getUid() <= 0) {
            return null;
        }
        return articleService.getMyList(userInfo.getUid());
    }

    /**
     * 获取我的文章数量
     *
     * @param request
     * @return
     */
    @RequestMapping("myartcount")
    public int myArtCount(HttpServletRequest request) {
        UserInfo userInfo = SessionUtil.getLoginUser(request);
        if (userInfo != null && userInfo.getUid() > 0) {
            return articleService.myArtCount(userInfo.getUid());
        }
        return 0;
    }

    /**
     * 获取分页列表
     *
     * @param psize
     * @param pindex
     * @return
     */
    @RequestMapping("/list")
    public List<ArticleInfo> getList(Integer psize, Integer pindex) {
        if (psize == null || pindex == null) {
            return null;
        }
        // 分页公式 : 计算偏移量
        int offset = psize * (pindex - 1);
        return articleService.getList(psize, offset);
    }

    /**
     * 计算分页功能的总页数 【不拦截】
     *
     * @param psize
     * @return
     */
    @RequestMapping("/totalpage")
    // 此处返回包装类, 是为了和前端中的 body.data != null相对应
    public Integer totalPage(Integer psize) {
        if (psize != null) {
            // 数据库中总条数
            int totalCount = articleService.getTotalCount();
            // 总页数
            int totalPage = (int) Math.ceil(totalCount * 1.0 / psize);
            return totalPage;
        }
        return null;
    }

    /**
     * 添加文章
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public Object addArtcile(ArticleInfo articleInfo, HttpServletRequest request) {
        // 1.非空校验（标题，内容)
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())
                || !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        // 2.组装数据（文章作者，标题，内容，简介）
        UserInfo userInfo = SessionUtil.getLoginUser(request);
        if (userInfo == null || userInfo.getUid() <= 0) {
            // 无效对象或者对象为空
            return AjaxResult.fail(-2, "请先登录！");
        }
        // 作者
        articleInfo.setUid(userInfo.getUid());
        String description = articleInfo.getContent();
        if (description.length()>MAX_DESCRIPTION_LENGTH){
            description=description.substring(0,MAX_DESCRIPTION_LENGTH);
        }
        // 简介
        articleInfo.setDescription(description);
        int result = articleService.addArticle(articleInfo);
        if (result==1){
            return AjaxResult.success("添加成功！",1);
        }else{
            return AjaxResult.fail(-3,"添加失败！");
        }
    }

    /**
     * 根据aid查询博客详情（起辅助作用：对修改页面）
     * @param aid
     * @return
     */
    @RequestMapping("/mydetail")
    public Object getMyDetail(Long aid){
        // 1.非空校验
        if (aid==null||aid<=0){
            return AjaxResult.fail(-1,"非法参数！");
        }
        // 2.操作数据库
        ArticleInfo articleInfo = articleService.getDetailByAid(aid);
        // 3.将结果返回给前端
        return AjaxResult.success(articleInfo);
    }

    /**
     * 修改文章
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/update")
    public Object updateArticle(ArticleInfo articleInfo,HttpServletRequest request){
        // 1.非空校验
        if (articleInfo==null||!StringUtils.hasLength(articleInfo.getTitle())
                ||!StringUtils.hasLength(articleInfo.getContent())
                ||articleInfo.getAid()<=0){
            return AjaxResult.fail(-1,"非法参数！");
        }
        // 2.组装数据
        UserInfo userInfo = SessionUtil.getLoginUser(request);
        if (userInfo==null||userInfo.getUid()<=0){
            return AjaxResult.fail(-2,"请先登录！");
        }
        // 作者
        articleInfo.setUid(userInfo.getUid());
        String description = articleInfo.getContent();
        if (description.length()>MAX_DESCRIPTION_LENGTH){
            description=description.substring(0,MAX_DESCRIPTION_LENGTH);
        }
        // 简介
        articleInfo.setDescription(description);
        // 3.操作数据库
        int result = articleService.updateArticle(articleInfo);
        // 4.返回结果给前端
        if (result==1){
            return AjaxResult.success("修改成功！",1);
        }else{
            return AjaxResult.fail(-3,"修改失败！");
        }
    }

    /**
     * 删除博客
     * @param aid
     * @param request
     * @return
     */
    @RequestMapping("/delete")
    public Object deleteArticle(Long aid,HttpServletRequest request){
        // 1.非空校验
        if (aid==null||aid<=0){
            return AjaxResult.fail(-1,"非法参数！");
        }
        // 2.获取登录用户
        UserInfo userInfo = SessionUtil.getLoginUser(request);
        if (userInfo==null||userInfo.getUid()<=0){
            return AjaxResult.fail(-2,"请先登录！");
        }
        ArticleInfo articleInfo = articleService.getDetailByAid(aid);
        if (articleInfo==null){
            return AjaxResult.fail(-5,"查询不到该文章！");
        }
        if (articleInfo.getUid()!=userInfo.getUid()){
            return AjaxResult.fail(-4,"不能删除别人的文章！");
        }
        // 3.操作数据库
        int result = articleService.deleteArticle(aid, userInfo.getUid());
        if (result==1){
            return AjaxResult.success("删除成功！",1);
        }else{
            return AjaxResult.fail(-3,"删除失败");
        }
    }


    /**
     * 获取文章详细信息（查看详情）
     * @param aid
     * @return
     */
    @RequestMapping("/detail")
    public Object getDetail(Long aid){
        // 1.参数校验
        if (aid == null || aid <= 0) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        // 2.查询数据库中的文章信息
        ArticleInfoVO articleInfoVO = articleService.getDetail(aid);
        if (articleInfoVO == null || articleInfoVO.getAid() <= 0) {
            return AjaxResult.fail(-2, "文章查询失败！");
        }
        // 3.组装数据，查询当前用户总共发表的文章数
        int count = articleService.myArtCount(articleInfoVO.getUid());
        articleInfoVO.setArtCount(count);
        // 4.将最终组装好的数据返回给前端
        return AjaxResult.success(articleInfoVO);
    }


    /**
     * 更新阅读人数
     *
     * @param aid
     * @return
     */
    @RequestMapping("/rcount")
    public Object updateRCount(Long aid) {
        // 参数校验
        if (aid == null || aid <= 0) {
            return AjaxResult.fail(-1, "参数有误！");
        }
        // 修改数据库
        int result = articleService.updateRCount(aid);
        // 将结果返回给前端
        return AjaxResult.success(result);
    }
}
